package com.tongda.menu.activity;

import java.io.IOException;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.WeakHashMap;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tongda.core.common.Constants;
import com.tongda.core.common.KernalApplication;
import com.tongda.core.repository.MenuCartDao;
import com.tongda.core.repository.MenuDishDao;
import com.tongda.core.service.BillService;
import com.tongda.core.service.DishService;
import com.tongda.core.service.TableService;
import com.tongda.core.service.UserService;
import com.tongda.core.utils.ActivityUtil;
import com.tongda.core.utils.DishUtil;
import com.tongda.core.utils.SharedPreferencesUtils;
import com.tongda.core.vo.Bill;
import com.tongda.core.vo.CancelDishReason;
import com.tongda.core.vo.Dish;
import com.tongda.core.vo.DishesSetDishes;
import com.tongda.core.vo.MobileRspResult;
import com.tongda.menu.R;
import com.tongda.menu.adapter.OrderedDishAdapter;
import com.tongda.menu.adapter.TuicaiAdapter;
import com.tongda.menu.util.ActivityMenuUtil;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

public class CartActivity extends BaseActivity{
	    private static int urgeTimer = 30;
	    
		public BigDecimal totalPrice = new BigDecimal(0);
		public BigDecimal billServiceMoney = new BigDecimal(0);
		public TextView billtotalMoney;
		public TextView billNumStr;
		public TextView dishestotalPriceTv;
		public String billNotesStr;
		public boolean canSpecialPrice = true;
		public  float totalNum = 0;
		
		protected Bill bill;
		
	    private Map<String, Object> params = new WeakHashMap<String, Object>();
		private KernalApplication application;
		private ListView orderListView;
		private List<Dish> datas;
		private OrderedDishAdapter adapter;   
		private MenuCartDao ordered_dish_dao;
		private MenuDishDao dish_dao;
		private DishUtil dishUtil;
		private Dish billNotes;
		private String billId;
		private TextView tableNoTv;
		private TextView peopleNumTv;
		private TextView billserviceStr;
		private TextView billserviceMoneyTv;
		private TextView billNotesTv;
		private Button billNoteBtn;
		private Button billCuiCaiBtn;
		private Button billClearBtn;
		private Button billDiancaiBtn;
		private Button billCallBtn;
		private Button billOrderBtn;
		private String username;
		private String password;
		// 退菜原因list
		private List<CancelDishReason> reasons;
		// 选中的退菜原因id
		private String reasonsId="";
		//最低消费的字符串
		private String consumeLowStr;
		//是否享受特价
		private FrameLayout noDishLy;
		private TextView goOrderTv;
		private String order = "no";
		private ImageView editImv;
		
		Handler billUrgeHandler = new Handler();
		Runnable billUrgeRunnable = new Runnable() {
			
			@Override
			public void run() {
				new BillurgeTimerTask().execute(urgeTimer);
				billUrgeHandler.postDelayed(billUrgeRunnable, 10000);
				
			}
		};

		@Override
		protected void onCreate(Bundle savedInstanceState) {
			super.onCreate(savedInstanceState);
			setContentView(R.layout.cart);
			application = KernalApplication.getInstance();
			ordered_dish_dao = MenuCartDao.getInstance(this);
			dish_dao = MenuDishDao.getInstance(this);
			dishUtil = DishUtil.getInstance(this);
			
			tableNoTv = (TextView)findViewById(R.id.cart_tableNOTv);
			billserviceStr = (TextView)findViewById(R.id.ordered_billserviceStr);
			billNumStr = (TextView)findViewById(R.id.ordered_dishesnumTv);
			dishestotalPriceTv = (TextView)findViewById(R.id.ordered_dishestotalPriceTv);
			billserviceMoneyTv = (TextView)findViewById(R.id.ordered_billserviceMoney);
			billtotalMoney = (TextView)findViewById(R.id.ordered_billtotalMoney);
			billNotesTv = (TextView)findViewById(R.id.ordered_billNotes);
			billNoteBtn = (Button)findViewById(R.id.ordered_billNoteBtn);
			billCuiCaiBtn = (Button)findViewById(R.id.ordered_billCuiCaiBtn);
			billCuiCaiBtn.setEnabled(false);
			billClearBtn = (Button)findViewById(R.id.ordered_billClearBtn);
			billDiancaiBtn = (Button)findViewById(R.id.ordered_billDiancaiBtn);
			billCallBtn = (Button)findViewById(R.id.ordered_billCallBtn);
			billOrderBtn = (Button)findViewById(R.id.ordered_billOrderBtn);
			noDishLy = (FrameLayout)findViewById(R.id.cart_noDish);
			goOrderTv = (TextView)findViewById(R.id.cart_go_order);
			editImv = (ImageView)findViewById(R.id.cart_edit_imv);
			
			Intent intent=getIntent();
			if(intent!=null){
				if(intent.getStringExtra("order")!=null && intent.getStringExtra("order").equals("yes")){
					 order = intent.getStringExtra("order");
				}
			}
		}
		
		@Override
		protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		if(intent.getStringExtra("order")!=null && intent.getStringExtra("order").equals("yes")){
			 order = intent.getStringExtra("order");
		}
		}
		
		@SuppressWarnings("unchecked")
		@Override
		protected void onResume() {
		super.onResume();
		if(application.getMenuSelectedTable()!=null){
			 billId = application.getMenuSelectedTable().getBillId();
		}
		params.put("id",billId);
		peopleNumTv = (TextView)findViewById(R.id.cart_peopleNumTv);
		if(application.getMenuSelectedTable()!=null&&application.getMenuSelectedTable().getTabNo()!=null){
			tableNoTv.setText("餐台："+application.getMenuSelectedTable().getTabNo()+"号餐桌");
			peopleNumTv.setText("就餐人数："+application.getMenuSelectedTable().getPeopleCount()+"位");
		}
		//获取初始化所有菜的总价
		if(billId==null || billId.equals("")){
			billserviceStr.setVisibility(View.GONE);
			billNotesTv.setVisibility(View.GONE);
			datas = ordered_dish_dao.getAll("all");
			adapter = new OrderedDishAdapter(datas,CartActivity.this);
			orderListView = (ListView)findViewById(R.id.orderDishLv);
			orderListView.setAdapter(adapter); 
			//处理点菜的总个数
			for(Dish dish:datas){
				if(dish.getDishesStatus()!=null && !dish.getDishesStatus().equals("2")){
					float num = dish.getOrdersalenum();
					totalNum = totalNum+num;
				}
			}
			billNumStr.setText(Html.fromHtml("共"+"<font color='red'>"+totalNum+"</font>"+"份"));
		for(Dish dish:datas){
			if(dish.getDishesStatus()!=null && !dish.getDishesStatus().equals("2")){
				if(dish.getIsRulingPrice()!=null && dish.getIsRulingPrice().equals("1")){
		        	totalPrice = totalPrice.add(BigDecimal.valueOf(Float.valueOf(dish.getRulingPrice())).multiply(BigDecimal.valueOf(dish.getOrdersalenum())));
				}else{
					if(canSpecialPrice){
						if(dish.getSpecialPrice()!=null){
							totalPrice = totalPrice.add(dish.getSpecialPrice().multiply(BigDecimal.valueOf(dish.getOrdersalenum())));
						}else{
							totalPrice = totalPrice.add(dish.getPrice().multiply(BigDecimal.valueOf(dish.getOrdersalenum())));
						}
					}else{
						totalPrice = totalPrice.add(dish.getPrice().multiply(BigDecimal.valueOf(dish.getOrdersalenum())));
					}
				}
			}
		}
		dishestotalPriceTv.setText(totalPrice.toString());
		billtotalMoney.setText((totalPrice.add(billServiceMoney)).toString());
		
		if(datas.size()==0){
			noDishLy.setVisibility(View.VISIBLE);
			goOrderTv.setText(Html.fromHtml("您还没有点菜哦！"+"<font color='#a9d300'>"+"去点菜>>"+"</font>"));
		}else{
			noDishLy.setVisibility(View.INVISIBLE);
		}
		}else{
			new getBillDetailTask().execute(params);
		}
		
		//处理全单备注
		String[] ladu_showArr = new String[] { "默认", "不辣", "微辣", "中辣", "辣", "特辣" };
		if(application.getBillNotes()!=null){
		    billNotes = application.getBillNotes();
			String laduStr = "";
		    if(billNotes.getLadu_value()!=0){
		    	laduStr = ladu_showArr[Integer.valueOf(billNotes.getLadu_value())];
		    }
		    billNotesTv.setVisibility(View.VISIBLE);
			billNotesTv.setText("全单备注："+billNotes.getTasteNameArray()+billNotes.getAvoidfoodNameArray()+laduStr+billNotes.getBillnotes());
		}
		
		
		billNoteBtn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(ActivityMenuUtil.checkNetworkState(CartActivity.this)){
        	    totalNum = 0;
        	    totalPrice = new BigDecimal(0);
				Intent intent  = new Intent(CartActivity.this,CartEditActivity.class);
				intent.putExtra("type", "bill");
				intent.putExtra("billId", billId);
				if(bill!=null && bill.getNotes()!=null){
					intent.putExtra("billNotes", bill.getNotes());
				}
				if(bill!=null && bill.getPungentLevel()!=null){
					intent.putExtra("punLevel", bill.getPungentLevel());
				}
				intent.putExtra("billNotesStr", billNotesStr);
				startActivity(intent);
				}else{ActivityUtil.Toast(CartActivity.this, "请开启设备网络环境", false, false);}
			}
		});
		//全单催菜
		billCuiCaiBtn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(ActivityMenuUtil.checkNetworkState(CartActivity.this)){
					--urgeTimer;
					billUrgeHandler.postDelayed(billUrgeRunnable,10000);
					if(urgeTimer>=29){
						new BillurgeTask().execute(billId);
					}else{
						Toast("您刚刚催过菜了,请稍等......");
					}
				}else{ActivityUtil.Toast(CartActivity.this, "请开启设备网络环境", false, false);}
			}
		});
		
		billClearBtn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
		        Dialog dialog = new AlertDialog.Builder(CartActivity.this). 
		                setTitle("您确定清空菜肴吗？"). 
		                setPositiveButton("确定", new DialogInterface.OnClickListener() { 
		                     
		                    @Override 
		                    public void onClick(DialogInterface dialog, int which) { 
		                    	    ordered_dish_dao.clearOrderDish();
		                    	    dish_dao.clearDishOrderNum();
		                    	    if(billId!=null && datas.size()>0){
			                    	    clearAllDinerDishesThread.start();
			                    	    try {
											clearAllDinerDishesThread.join();
										} catch (InterruptedException e) {
											e.printStackTrace();
										}
		                    	    }
		                    	    totalNum = 0;
		                    	    totalPrice = new BigDecimal(0);
		                    	    application.setBillNotes(null);
		                    	    CartActivity.this.onResume();
		                    	    dialog.dismiss();
		                    } 
		                }). 
		                setNegativeButton("取消", new DialogInterface.OnClickListener() {
		                     
		                    @Override 
		                    public void onClick(DialogInterface dialog, int which) { 
		                    	CartActivity.this.onResume();
		                    	dialog.dismiss();
		                    } 
		                }). 
		                create(); 
		        dialog.show();
			}
		});
		//继续点菜
		billDiancaiBtn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				application.setMenuMainIsRefresh(true);
				//购物车和账单融合后为了让首页正确显示当前的已点菜品数量增加的方法
				Cart2Main();
			}
		});
		//呼叫下单
		billCallBtn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(ActivityMenuUtil.checkNetworkState(CartActivity.this)){
				if(billId==null){
					Toast("请先开台再呼叫下单");
				}else if(!hasUnOrderDish(datas)){
					Toast("您没有未下单的菜肴,无需呼叫下单服务!");
				}else{
					new CallOrder().execute(application.getMenuSelectedTable().getTabNo());
				}
				}else{
					ActivityUtil.Toast(CartActivity.this, "请开启设备网络环境", false, false);
				}
			}
		});
		
		//下单
		billOrderBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				final Handler judgeBillHandler = new Handler(){
					@Override
					public void handleMessage(Message msg) {
						super.handleMessage(msg);
						String billStatus = msg.getData().getString("billStatus");
						
						if(billId==null){
							Toast("请先验证开台再下单!");
							showVerifyId("openTable",null);
						}
						else if(!hasUnOrderDish(datas)){
							Toast("您没有未下单的菜肴!");
						}
						else if(dishestotalPriceTv.getText().toString()!=null && consumeLowStr!=null && !dishestotalPriceTv.getText().toString().equals("") && !consumeLowStr.equals("") && Float.valueOf(dishestotalPriceTv.getText().toString())<Float.valueOf(consumeLowStr)){
							Toast("您的消费不满足最低消费,无法下单!");
						}else if(billStatus.equals("3")){
							Toast("该餐台已经结账,无法下单!");
						}else{
							showVerifyId("order",null);
						}
					}
				};
				
				Thread judgeBillStatus = new Thread(new Runnable() {
					
					@Override
					public void run() {
						String billStatus = "";
						if(billId!=null){
							 billStatus = BillService.getBillStatus(billId);
						}
						Message msg = judgeBillHandler.obtainMessage();
						Bundle data = new Bundle();
						data.putString("billStatus", billStatus);
						msg.setData(data );
						judgeBillHandler.sendMessage(msg);
					}
				});
				
				if(ActivityMenuUtil.checkNetworkState(CartActivity.this)){
					judgeBillStatus.start();
				}else{
					ActivityUtil.Toast(CartActivity.this, "请开启设备网络环境", false, false);
				}
			}
		});
		
		
		goOrderTv.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				application.setMenuMainIsRefresh(true);
				//购物车和账单融合后为了让首页正确显示当前的已点菜品数量增加的方法
				Cart2Main();
				CartActivity.this.finish();
			}
		});
		
		if(order.equals("yes")){
			new OrderTask().execute(params);
		}
		
		}
		
		@Override
		protected void loadData() {
			List<Dish> billDishes = dealDinnerBillDishes(bill.getDishes());
			if(billDishes!=null){
				datas.addAll(billDishes);
			}
			
			for(Dish dish:datas){
				//此处
				if(dish.getDishesStatus()!=null && !dish.getDishesStatus().equals("2")){
					if(dish.getIsRulingPrice()!=null && dish.getIsRulingPrice().equals("1")){
			        	totalPrice = totalPrice.add(BigDecimal.valueOf(Float.valueOf(dish.getRulingPrice())).multiply(BigDecimal.valueOf(dish.getOrdersalenum())));
					}else{
						if(canSpecialPrice){
							if(dish.getSpecialPrice()!=null){
								totalPrice = totalPrice.add(dish.getSpecialPrice().multiply(BigDecimal.valueOf(dish.getOrdersalenum())));
							}else{
								totalPrice = totalPrice.add(dish.getPrice().multiply(BigDecimal.valueOf(dish.getOrdersalenum())));
							}
						}else{
							totalPrice = totalPrice.add(dish.getPrice().multiply(BigDecimal.valueOf(dish.getOrdersalenum())));
						}
					}
				}
			}
			
			//处理点菜的总个数
			for(Dish dish:datas){
				if(dish.getDishesStatus()!=null &&!dish.getDishesStatus().equals("2")){
					float num = dish.getOrdersalenum();
					totalNum = totalNum+num;
				}
			}
		}
		
		@Override
		protected void describeView() {
			adapter = new OrderedDishAdapter(datas,CartActivity.this);
			orderListView = (ListView)findViewById(R.id.orderDishLv);
			orderListView.setAdapter(adapter); 
			billNumStr.setText(Html.fromHtml("共"+"<font color='red'>"+totalNum+"</font>"+"份"));
			dishestotalPriceTv.setText(totalPrice.toString());
			billserviceMoneyTv.setText(Html.fromHtml("服务费: "+"<font color='red'>"+billServiceMoney+bill.getServiceChargeType()+"</font>"));
			billtotalMoney.setText((totalPrice.add(billServiceMoney)).toString());
			if(datas.size()==0){
				noDishLy.setVisibility(View.VISIBLE);
				goOrderTv.setText(Html.fromHtml("您还没有点菜哦！"+"<font color='#a9d300'>"+"去点菜>>"+"</font>"));
			}else{
				noDishLy.setVisibility(View.INVISIBLE);
			}
			boolean cantclear = false;
			for(Dish dish:datas){
				if(dish.getDishesStatus()!=null && (dish.getDishesStatus().equals("1")||dish.getDishesStatus().equals("2"))){
					cantclear = true;
					break;
				}
			}
			
			if(cantclear){
				    billClearBtn.setEnabled(false);
				}else{
					 billClearBtn.setEnabled(true);
				}
			
			boolean canturdge = false;
			for(Dish dish:datas){
				if(dish.getDishesStatus()!=null && dish.getDishesStatus().equals("1")){
					canturdge = true;
					break;
				}
			}
			
			if(canturdge){
				billCuiCaiBtn.setEnabled(true);
			}else{
					billCuiCaiBtn.setEnabled(false);
			}
			
			if(bill!=null){
				String laduStr="";
				String notes = "";
				String tastNameArray ="";
				String avoidFoodArray = "";
				String[] ladu_showArr = new String[] { "默认", "不辣", "微辣", "中辣", "辣", "特辣" };
			    if(bill.getTasteNameArray()!=null && !bill.getTasteNameArray().equals("null")){
			    	tastNameArray = bill.getTasteNameArray();
			    }
			    if(bill.getAvoidfoodNameArray()!=null && !bill.getAvoidfoodNameArray().equals("null")){
			    	avoidFoodArray = bill.getAvoidfoodNameArray();
			    }
			    if(bill.getPungentLevel()!=null && !bill.getPungentLevel().equals("0")){
			    	laduStr = ladu_showArr[Integer.valueOf(bill.getPungentLevel())];
			    }
			    if(bill.getNotes()!=null && !bill.getNotes().equals("null")){
			    	notes = bill.getNotes();
			    }
			    billNotesStr = tastNameArray+avoidFoodArray+laduStr+notes;
				billNotesTv.setText("全单备注："+tastNameArray+avoidFoodArray+laduStr+notes);
				if(billNotesTv.getText().equals("全单备注：")){
					billNotesTv.setVisibility(View.GONE);
				}else{
					billNotesTv.setVisibility(View.VISIBLE);
				}
				
				if((bill.getTasteNameArray()!=null && !bill.getTasteNameArray().equals("")) || (bill.getAvoidfoodNameArray()!=null && !bill.getAvoidfoodNameArray().equals("")) || (bill.getPungentLevel()!=null && !bill.getPungentLevel().equals("0"))||(bill.getNotes()!=null && !bill.getNotes().equals(""))){
						application.setBillNotes(null);
						billNotes=null;
			      }else{
						 if(application.getBillNotes()!=null){
								//处理全单备注
							    billNotes = application.getBillNotes();
							    if(billNotes.getLadu_value()!=0){
							    	laduStr = ladu_showArr[Integer.valueOf(billNotes.getLadu_value())];
							    }
							    billNotesTv.setVisibility(View.VISIBLE);
								billNotesTv.setText("全单备注："+billNotes.getTasteNameArray()+billNotes.getAvoidfoodNameArray()+laduStr+billNotes.getBillnotes());
							}
						}
			      }

			editImv.setVisibility(View.VISIBLE);
			editImv.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					Intent intent = new Intent(CartActivity.this, OpenTableActivity.class);
					intent.putExtra("cartEdit", "cartEdit");
					intent.putExtra("dinnerStatus", "2");
					intent.putExtra("billId", billId);
					startActivity(intent);
				}
			});
			
			billDiancaiBtn.setEnabled(true);
			billOrderBtn.setEnabled(true);
			setBlockScreen(false);
		}
		public class getBillDetailTask extends AsyncTask<Map<String, Object>, Void, Bill>{
			

			@Override
			protected void onPreExecute() {
				super.onPreExecute();
				datas = ordered_dish_dao.getAll("all");
				billDiancaiBtn.setEnabled(false);
				billOrderBtn.setEnabled(false);
				//获取账单的时候屏蔽回退键,功效同“继续点菜”
				setBlockScreen(true);
				
			}

			@Override
			protected Bill doInBackground(Map<String, Object>... params) {
					bill = BillService.showDetail(params[0], false);
				return null;
			} 
			
			@Override
			protected void onPostExecute(Bill result) {
				super.onPostExecute(result);
				if(bill!=null){
					billServiceMoney = bill.getServiceChargeMoney();
					String serviceStr = bill.getServiceStr();
					billserviceStr.setVisibility(View.VISIBLE);
					billserviceStr.setText("服务费"+serviceStr);
					//处理服务描述字符串，拿出最低消费的字符串值
					consumeLowStr = serviceStr.substring(serviceStr.indexOf("最低消费")+4,serviceStr.lastIndexOf("元"));
					if(serviceStr.contains("不享受特价")){
						canSpecialPrice =false;
					}else{
						canSpecialPrice =true;
					}
					initCurrentView();
					
				}else{
//					Toast.makeText(CartActivity.this, "获取账单失败正在重新获取", Toast.LENGTH_SHORT).show();
					cancel(true);
					Intent intent = new Intent(CartActivity.this,CartActivity.class);
					startActivity(intent);
				}
			}
		}
		
		
		
		public  void Toast(String taostStr){
			LayoutInflater inflater = getLayoutInflater();
			View layout = inflater.inflate(R.layout.toast_layout,
			(ViewGroup) findViewById(R.id.toast_layout_root));

			ImageView image = (ImageView) layout.findViewById(R.id.image);
			image.setImageResource(R.drawable.toastimv);
			TextView text = (TextView) layout.findViewById(R.id.text);
			text.setGravity(Gravity.CENTER_VERTICAL);
			text.setText(taostStr);

			Toast toast = new Toast(getApplicationContext());
			toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
			toast.setDuration(Toast.LENGTH_SHORT);
			toast.setView(layout);
			toast.show();
		}
		
		public void showCartEditActivity(String type,String id,Dish dish){
			totalNum = 0;
    	    totalPrice = new BigDecimal(0);
			Intent intent  = new Intent(CartActivity.this,CartEditActivity.class);
			intent.putExtra("type", type);
			intent.putExtra("dish", dish);
			startActivity(intent);
		}

		public BigDecimal getTotalPrice() {
			return totalPrice;
		}

		public void setTotalPrice(BigDecimal totalPrice) {
			this.totalPrice = totalPrice;
		}
		
		@Override
		public boolean onKeyDown(int keyCode, KeyEvent event) {
			if(!isBlockScreen()){
				if(keyCode==KeyEvent.KEYCODE_BACK){
					application.setMenuMainIsRefresh(true);
					Cart2Main();
					CartActivity.this.finish();
				}
				return super.onKeyDown(keyCode, event);
			}else{
				return true;
			}
		}
		
		public class OrderTask extends AsyncTask<Map<String, Object>, Void, Boolean>{
			
			private List<Dish> unorderDatas;
			private Dialog dialog;
			boolean result=true;

			@Override
			protected void onPreExecute() {
				super.onPreExecute();
				
				dialog = new Dialog(CartActivity.this, R.style.TransparentWindowStyle);
				View view = View.inflate(CartActivity.this, R.layout.wait_layout, null);
				dialog.show();
				dialog.setCanceledOnTouchOutside(false);
				dialog.setContentView(view);
				/*
				 * 重新计算一下获取所有未下单的本地菜肴
				 * */
				unorderDatas = ordered_dish_dao.getAll("unorder");
			}
			
			
			@Override
			protected Boolean doInBackground(Map<String, Object>... params) {
        		if(!UserService.getCurrentUserHasPermission("frontdesk_index_xiadan:create")){
        			result=false;
    		      }else {
							for(Dish dish:unorderDatas){
								String dinerBillDisheId;
									if(dish.getIsSet().equals("true")){
//										 dinerBillDisheId = DishService.orderDishSet(billId, dish.getDishesId(), String.valueOf(dish.getOrdersalenum()),"3");
										 MobileRspResult r = DishService.orderDishSet(billId, dish.getDishesId(), String.valueOf(dish.getOrdersalenum()), dish.getDishSetDishes(), "3");
										 Map<String, String> map = r.getMap();
										 dinerBillDisheId = map.get("dinerBillDisheId");
									}else{
//										 dinerBillDisheId = DishService.orderDish(billId, dish.getDishesId(), String.valueOf(dish.getOrdersalenum()),"2",dish.getIsRulingPrice(),dish.getRulingPrice());
										 MobileRspResult r = DishService.orderDish(billId, dish.getDishesId(),  String.valueOf(dish.getOrdersalenum()), "2");
										 Map<String, String> map = r.getMap();
										 dinerBillDisheId = map.get("dinerBillDisheId");
									}
									synchronized (Constants.objectLock) {
										if(dinerBillDisheId.equals("")){
											result=false;
										}else{
											result = true;
											ordered_dish_dao.addBillDisheId(String.valueOf(dish.get_id()), dinerBillDisheId);
										}
										
									}
							}
						//重新获取数据,拿到账单菜肴id
							if(result==true){
								unorderDatas = ordered_dish_dao.getAll("unorder");
								for( Dish dish:unorderDatas){
									if(dish.getIsSet().equals("true")){
										String dsJsonStr = dishUtil.dsDishes2Json(dish.getDsDishes());
										BillService.editDishesSetReplace(dish.getDinerBillDisheId(),dsJsonStr);
										BillService.savePrbz("dish", dish.getDinerBillDisheId(), dish.getTasteIdArray(), dish.getTasteNameArray(), dish.getAvoidfoodIdArray(), dish.getAvoidfoodNameArray(), dish.getLadu_value(), dish.getBillnotes(), "1");
									}else{
										BillService.savePrbz("dish", dish.getDinerBillDisheId(), dish.getTasteIdArray(), dish.getTasteNameArray(), dish.getAvoidfoodIdArray(), dish.getAvoidfoodNameArray(), dish.getLadu_value(), dish.getBillnotes(), "0");
									}
									synchronized (Constants.objectLock) {
										  ordered_dish_dao.updateDishStatus(String.valueOf(dish.get_id()), "1");
									}
								}
							if(billNotes!=null){
								BillService.savePrbz("bill", billId, billNotes.getTasteIdArray(), billNotes.getTasteNameArray(), billNotes.getAvoidfoodIdArray(), billNotes.getAvoidfoodNameArray(), billNotes.getLadu_value(), billNotes.getBillnotes(), null);
							}
								BillService.xiadan(billId);
							}
				}
				return result;
			}
			
			@Override
			protected void onPostExecute(Boolean result) {
				super.onPostExecute(result);
				order = "no";
				dialog.dismiss();
				if(result==true){
					Toast("为您下单成功!");
					//下单之后清空购物车
					ordered_dish_dao.clearOrderDish();
					//下单之后清空主界面中菜肴的已点数量
					dish_dao.clearDishOrderNum();
					
	        	    totalNum = 0;
	        	    totalPrice = new BigDecimal(0);
	        	    
	        	    application.setBillNotes(null);
					CartActivity.this.onResume();
					cancel(true);
				}else{
					Toast("下单失败,您可能没有下单权限!");
				}
			}
		}
		
		@Override
		protected void onPause() {
		super.onPause();
	    totalNum = 0;
	    totalPrice = new BigDecimal(0);
		}
		
		//控制全单催菜时间的异步任务
		public class BillurgeTimerTask extends AsyncTask<Integer, Void,Void>{

			@Override
			protected Void doInBackground(Integer... params) {
				if(urgeTimer>0 && urgeTimer<30){
					--urgeTimer;
					if(urgeTimer==0){
						urgeTimer = 30;
					}
				}
				Log.i("urgeTimer", String.valueOf(urgeTimer));
				return null;
			}
			
			@Override
			protected void onPostExecute(Void result) {
				super.onPostExecute(result);
				cancel(true);
			}
		}
		//全单催菜的异步任务
		public class BillurgeTask extends AsyncTask<String, Void, Void>{

			@Override
			protected Void doInBackground(String... params) {
				BillService.urgebill(params[0]);
				return null;
			}
			
			@Override
			protected void onPostExecute(Void result) {
				super.onPostExecute(result);
				Toast("桌号"+application.getMenuSelectedTable().getTabNo()+"全单催菜成功");
				cancel(true);
			}
		}
		
		/*
		 * 弹出身份验证的对话框，根据不同的参数走不同的方法
		 */
		@SuppressWarnings("unchecked")
		public void showVerifyId(final String param,final Dish dish){
			 totalNum = 0;
     	    totalPrice = new BigDecimal(0);
     	   boolean isRemUser = (Boolean) SharedPreferencesUtils.getParam(CartActivity.this, Constants.MENU_IS_REM_CURRENTUSER, false);
     	    if(!isRemUser){
    			final AlertDialog dialog = new AlertDialog.Builder(CartActivity.this).create();
    			View view = View.inflate(CartActivity.this, R.layout.dialog_verifyid, null);
    			dialog.setView(view,0,0,0,0);
    			dialog.setCancelable(false);
    			dialog.setCanceledOnTouchOutside(false);
    			dialog.show();
    			final EditText ID_Edt = (EditText)view.findViewById(R.id.verifyid_ID_edt);
    		    final EditText PD_Edt = (EditText)view.findViewById(R.id.verifyid_pw_edt);
    		    final ImageView cancelImv = (ImageView)view.findViewById(R.id.verifyid_cancle);
    			Button LG_Btn = (Button)view.findViewById(R.id.verifyid_login_btn);
    			final CheckBox isRemCb = (CheckBox)view.findViewById(R.id.verifyid_remId);
				isRemCb.setOnCheckedChangeListener(new OnCheckedChangeListener() {
					
					@Override
					public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
						if(isRemCb.isChecked()){
							Toast.makeText(CartActivity.this, "记住登录状态,后续操作不用验证账号", Toast.LENGTH_SHORT).show();
						}else{
							Toast.makeText(CartActivity.this, "取消记住登录状态,后续操作验证账号", Toast.LENGTH_SHORT).show();
						}
					}
				});
    			LG_Btn.setOnClickListener(new OnClickListener() {

    				private int result;

    				@SuppressWarnings("unchecked")
    				@Override
    				public void onClick(View v) {
    					 username = ID_Edt.getText().toString();
    					 password = PD_Edt.getText().toString();
    					 
    						Thread loginThread = new Thread(new Runnable() {
    							
    							@Override
    							public void run() {
    								result = UserService.login(CartActivity.this,username, password,false);
    							}
    						});
    						
    						
    					if(!username.equals("") && !password.equals("")){
    						loginThread.start();
    						try {
    							loginThread.join();
    						} catch (InterruptedException e) {
    							e.printStackTrace();
    						}
                            if(result==0){
								//把当前输入的账号密码记录到preference中
								SharedPreferencesUtils.setParam(CartActivity.this, Constants.USERNAME, username);
								SharedPreferencesUtils.setParam(CartActivity.this, Constants.PASSWORD, password);
								SharedPreferencesUtils.setParam(CartActivity.this, Constants.MENU_IS_REM_CURRENTUSER, isRemCb.isChecked());
                            	if(param.equals("order")){
        							new OrderTask().execute(params);
                            	}
                            	
                            	if(param.equals("tuicai")){
                            		new initTuicaiTask().execute(dish);
                            	}
                            	if(param.equals("openTable")){
    								Intent intent = new Intent(CartActivity.this,TableActivity.class);
    								intent.putExtra("from", "cartActivity");
    								intent.putExtra("order", "yes");
    								startActivity(intent);
                            	}
                            	
    							dialog.dismiss();
    						}else{
    							ActivityUtil.Toast(CartActivity.this, "身份验证失败", false, false);
    						}
    					}else{
    						ActivityUtil.Toast(CartActivity.this, "用户名或密码为空", false, false);
    					}
    				}
    			});
    			
    			cancelImv.setOnClickListener(new OnClickListener() {
    				
    				@Override
    				public void onClick(View v) {
    					CartActivity.this.onResume();
    					dialog.dismiss();
    				}
    			});
     	    }else{
               	if(param.equals("order")){
						new OrderTask().execute(params);
                	}
                	
                	if(param.equals("tuicai")){
                		new initTuicaiTask().execute(dish);
                	}
                	if(param.equals("openTable")){
						Intent intent = new Intent(CartActivity.this,TableActivity.class);
						intent.putExtra("from", "cartActivity");
						intent.putExtra("order", "yes");
						startActivity(intent);
                	}
   	    }

		}
		
		
		public class initTuicaiTask extends AsyncTask<Dish, Void, List<CancelDishReason>>{
			private Dish dish;
			private float initalCount=1;
			private Dialog dialog;
			private boolean limite = false;
			
			@Override
			protected void onPreExecute() {
				super.onPreExecute();
				dialog = new Dialog(CartActivity.this, R.style.TransparentWindowStyle);
				View view = View.inflate(CartActivity.this, R.layout.wait_layout, null);
				dialog.show();
				dialog.setCanceledOnTouchOutside(false);
				dialog.setContentView(view);
			}
			
			@Override
			protected List<CancelDishReason> doInBackground(Dish... params) {
				limite = UserService.getCurrentUserHasPermission("frontdesk_bill_tuicai:create");
        		if(!limite){
        			reasons = null;
				}else{
				dish = params[0];
				reasons = BillService.getTuiCaiYuanYin();}
				return reasons;
			}
			
			@Override
			protected void onPostExecute(List<CancelDishReason> result) {
				super.onPostExecute(result);
				dialog.dismiss();
				if(reasons==null){
					Toast("您没有退菜权限");
					return;
				}
				if(dish!=null){
					initalCount = dish.getOrdersalenum();
				}
				
				final AlertDialog.Builder builder = new Builder(CartActivity.this);
				builder.setTitle("请选择").setIcon(android.R.drawable.ic_dialog_info);
				View dialogview = getLayoutInflater().inflate(R.layout.dialogview, null);
				builder.setView(dialogview);
				final AlertDialog alertDialog = builder.show();

				ImageView minusbtn = (ImageView) dialogview.findViewById(R.id.minus);
				final ImageView addbtn = (ImageView) dialogview.findViewById(R.id.add);
				final TextView count = (TextView) dialogview.findViewById(R.id.tuicai_count);
				count.setText(initalCount+ "");
				Button confirm = (Button) dialogview.findViewById(R.id.dialog_button_ok);
				Button cancel = (Button) dialogview.findViewById(R.id.dialog_button_cancel);
				
				final RadioButton XhRoBtn = (RadioButton)dialogview.findViewById(R.id.yixiaohaoyuanliao);
				final RadioButton WxhRoBtn = (RadioButton) dialogview.findViewById(R.id.weixiaohaoyuanliao);
				
				final EditText myReasonEdt = (EditText)dialogview.findViewById(R.id.cancel_myreason);
				String[] str;
					str = new String[reasons.size()];
					for (int i = 0; i < reasons.size(); i++) {
						str[i] = reasons.get(i).getName();
					}

					ListView selectview = (ListView) dialogview.findViewById(R.id.select_listview);

					final TuicaiAdapter tArrayAdapter = new TuicaiAdapter(CartActivity.this, reasons);

					selectview.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
					selectview.setAdapter(tArrayAdapter);

					selectview.setOnItemClickListener(new OnItemClickListener() {

						@Override
						public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
							setReasonsId(reasons.get(position).getReaId());
							tArrayAdapter.setSelection(position);
							tArrayAdapter.notifyDataSetChanged();
							myReasonEdt.setEnabled(false);
							myReasonEdt.setText("");
						}

					});

					minusbtn.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							float tuicaicount = Float.parseFloat(count.getText().toString());
							if (tuicaicount > 1) {
								tuicaicount = tuicaicount - 1;
							}
							count.setText(tuicaicount + "");

						}
					});

					addbtn.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							float tuicaicount = Float.parseFloat(count.getText().toString());
							if (tuicaicount < initalCount) {
								tuicaicount = tuicaicount + 1;
							}
							count.setText(tuicaicount + "");
						}
					});

					confirm.setOnClickListener(new OnClickListener() {

						@SuppressWarnings("unchecked")
						@Override
						public void onClick(View v) {
							if(myReasonEdt.getText().toString().equals("") && getReasonsId().equals("")){
								Toast("请选择或输入退菜原因！");
							}else{
							Map<String, Object> map = new WeakHashMap<String, Object>();
								map.put("dishId", dish.getDinerBillDisheId());
								map.put("reasonId", getReasonsId());
								map.put("countStr", count.getText());
								map.put("newAddReason", myReasonEdt.getText().toString());
								
								
								map.put("dish", dish);
								map.put("orderNum", dish.getOrdersalenum());
								if(XhRoBtn.isChecked() || WxhRoBtn.isChecked()){
									if(WxhRoBtn.isChecked()){
										if(dish.getIsSet().equals("true")){
											map.put("backornot", true);
											map.put("isSet", "1");
										}else{
											map.put("backornot", true);
											map.put("isSet", "0");
										}
									}else{
										if(dish.getIsSet().equals("true")){
											map.put("backornot", false);
											map.put("isSet", "1");
										}else{
											map.put("backornot", false);
											map.put("isSet", "0");
										} 
									}
									new TuicaiTask().execute(map);
							    alertDialog.dismiss();
								}else{
									Toast("必须选择是否消耗原料");
								}
							}
						}
					});
					cancel.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View v) {
							Toast("取消退菜");
							CartActivity.this.onResume();
							alertDialog.dismiss();
						}
					});
					
					
			}
		}
		
		public class TuicaiTask extends AsyncTask<Map<String, Object>, Void, Void>{
			Map<String, Object> map;
			int _id;
			String dishId;
			String reasonId;
			String countStr;
			boolean backornot;
			String isSet;
			String newAddReason;
			
			Dish dish;
			float orderNum;
			@Override
			protected void onPreExecute() {
				super.onPreExecute();
				
			}

			@Override
			protected Void doInBackground(Map<String, Object>... params) {
				map = params[0];
				dishId = (String) map.get("dishId");
				reasonId = (String) map.get("reasonId");
				countStr = (String) map.get("countStr");
				backornot = (Boolean) map.get("backornot");
				isSet = (String) map.get("isSet");
				newAddReason=(String) map.get("newAddReason");
				
				dish = (Dish)map.get("dish");
				orderNum = (Float)map.get("orderNum");
				
				BillService.cancelDish(dishId, reasonsId, countStr, backornot, isSet,newAddReason);
				return null;
			}
			
			@Override
			protected void onPostExecute(Void result) {
				super.onPostExecute(result);
				Toast("退菜成功");
        	    totalNum = 0;
        	    totalPrice = new BigDecimal(0);
				CartActivity.this.onResume();
				cancel(true);
			}
		}
		
		public String getReasonsId() {
			return reasonsId;
		}

		public void setReasonsId(String reasonsId) {
			this.reasonsId = reasonsId;
		}
		
		private static long preorderTime;
		private static long postorderTime;
		public class CallOrder extends AsyncTask<String, Void, Boolean>{
			String tableNo;
			
			@Override
			protected void onPreExecute() {
				super.onPreExecute();
				preorderTime = System.currentTimeMillis();
			}
			
		@Override
		protected Boolean doInBackground(String... params) {
			tableNo = params[0];
			if(preorderTime-postorderTime<30000){
				return false;
			}else{
				TableService.callService(tableNo,"0", "电子菜谱:"+tableNo+"号餐台呼叫下单!");
				return true;
			}
		}
		
		@Override
		protected void onPostExecute(Boolean result) {
		      super.onPostExecute(result);
		      if(!result){
		    	    Toast("您刚刚已经呼叫了下单,请稍候...");
		      }else{
		    	    Toast("已呼叫服务员前来为您下单!");
		      }
		      postorderTime = System.currentTimeMillis();
		      cancel(true);
		}
	}
			
		public void showMenuShowActivity(String dishName){
			Intent intent  = new Intent();
			intent.setClass(CartActivity.this, ShowActivity.class);
			intent.putExtra("dishName", dishName );
			startActivity(intent);
			overridePendingTransition(R.anim.in_from_top, R.anim.out_to_top);
		}
		
//处理账单的菜肴(2.2.0之后优化)
		private List<Dish> dealDinnerBillDishes(List<Dish> tempbillDishes){
			if(tempbillDishes!=null && tempbillDishes.size()>0){
				for(Dish tempbillDish:tempbillDishes){
					tempbillDish.setSpecialPrice(tempbillDish.getRealUnitPrice());
					//5表示未下单，1表示已下单，3表示已退菜(状态属性)
					if(tempbillDish.getDishesStatus().equals("5")){
						tempbillDish.setDishesStatus("0");
					}
					if(tempbillDish.getDishesStatus().equals("1")){
						tempbillDish.setDishesStatus("1");
					}
					if(tempbillDish.getDishesStatus().equals("3")){
						tempbillDish.setDishesStatus("2");
					}
					//是否是套餐的属性
					if(tempbillDish.getIsSet().equals("0")){
						tempbillDish.setIsSet("false");
					}
					if(tempbillDish.getIsSet().equals("1")){
						tempbillDish.setIsSet("true");
						
						//套餐的子菜肴
						String dsDishesDesc = tempbillDish.getDishSetDishes();
						ObjectMapper objectmapper = new ObjectMapper();
						DishesSetDishes[] dsDishesArray;
						List<DishesSetDishes> dsDishes = null;
						try {
							dsDishesArray = objectmapper.readValue(dsDishesDesc, DishesSetDishes[].class);
							 dsDishes =Arrays.asList(dsDishesArray);
						} catch (JsonParseException e) {
							e.printStackTrace();
						} catch (JsonMappingException e) {
							e.printStackTrace();
						} catch (IOException e) {
							e.printStackTrace();
						}
						tempbillDish.setDsDishes(dsDishes);
					}
					//菜肴账单id的属性
					tempbillDish.setDinerBillDisheId(tempbillDish.getDishesId());
					tempbillDish.setDishesId(tempbillDish.getLocalDishesId());
					//份数的属性
					tempbillDish.setOrdersalenum(tempbillDish.getUnitNum());
					tempbillDish.setRulingPrice(tempbillDish.getRealUnitPrice().toString());
					//备注信息
					tempbillDish.setIsDinerDish("1");
				}
			}
			return tempbillDishes;
		}
		
		/*
		 * 更改账单菜肴数量的子线程
		 * */
		
		public void changeDinerBillDishNum(final String dinnerBillId,final String numStr, final String isSet){
			Thread changeNumThread = new Thread(new Runnable() {
				
				@Override
				public void run() {
					if(isSet.equals("true")){
					jiacaiSet(dinnerBillId,numStr);
					}else{
						jiacai(dinnerBillId, numStr);
					}
				}
			});
			changeNumThread.start();
		}
		
		/**
		 * 加菜请求
		 * 
		 * @param dishId
		 * @param saleNum
		 */
		public void jiacai(String dishId, String saleNum) {
			 BillService.updateDish(bill.getBillId(), dishId, saleNum,"0");
		}

		/**
		 * 加菜请求(套餐)
		 * 
		 * @param dishId
		 * @param saleNum
		 */
		public  void jiacaiSet(String dishId, String saleNum) {
			
			 BillService.updateDishSet(bill.getBillId(), dishId, saleNum,"0");
		}
		/**
		 * 账单菜肴的删菜操作
		 * 
		 */
		public void shancai(final String dbId, final String isSet){
			Thread deleteThread = new Thread(new Runnable() {
				
				@Override
				public void run() {
					BillService.shancai(billId, dbId, isSet);
				}
			});
			deleteThread.start();
		}
		
		//跳转到主界面的时候把账单菜肴的数据传递过去
		private void Cart2Main(){
			Intent intent = new Intent(CartActivity.this,MainActivity.class);
			if(billId!=null){
				if(bill!=null){
					List<Dish> dinerDishes = bill.getDishes();
					if(dinerDishes!=null){
						ArrayList<String>dinerDishesCategoryIds =  getdinerDishesCategoryId(dinerDishes);
						List<Dish> billDishes = dealDinnerBillDishes(bill.getDishes());
						intent.putExtra("dinerDishes", (Serializable)billDishes);
						intent.putStringArrayListExtra("dinerDishesCategoryIds", dinerDishesCategoryIds);
					}
				}
			}
			startActivity(intent);
			overridePendingTransition(R.anim.in_from_left, R.anim.out_to_right);
		}
		//处理账单菜肴把所有的菜肴的菜类id拿出来
		private ArrayList<String> getdinerDishesCategoryId(List<Dish> dinerDishes){
			ArrayList<String> categoryIds = new ArrayList<String>();
			if(dinerDishes!=null){
				for(Dish dinerDish:dinerDishes){
					for(	float i=0;i<dinerDish.getUnitNum();i++){
						categoryIds.add(dinerDish.getCategoryId());
					}
				}
			}
			return categoryIds;
		}
		
		//清空全部账单菜肴的子线程
		
	Thread clearAllDinerDishesThread = new Thread(new Runnable() {
		
		@Override
		public void run() {
    	    for(Dish dish:datas){
    	    	if(!dish.getIsDinerDish().equals("0")){
            		String isSet = null;
					if(dish.getIsSet().equals("false")){
						isSet="0";
					}else if(dish.getIsSet().equals("true")){
						isSet = "1";
					}
            	 	BillService.shancai(billId, dish.getDinerBillDisheId(), isSet);
    	    	}
    	    }
		}
	});
	
	//判断购物车中的菜肴是否有未下单的菜肴
	private boolean hasUnOrderDish(List<Dish> datas){
		boolean result = false;
		for(Dish dish:datas){
			if(dish.getDishesStatus()!=null && dish.getDishesStatus().equals("0")){
				result = true;
				break;
			}
		}
		return result;
	}

}
